package com.xnyzc.lhy.mis.service.impl.engine;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xnyzc.lhy.common.component.convert.DateToStringConverter;
import com.xnyzc.lhy.common.constant.MessageConstant;
import com.xnyzc.lhy.common.entity.Rv;
import com.xnyzc.lhy.common.exception.PangException;
import com.xnyzc.lhy.common.penum.EErrorCode;
import com.xnyzc.lhy.common.penum.cms.ERulesConditions;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.common.util.TokenUtil;
import com.xnyzc.lhy.mis.entity.dictionaries.OaSysDict;
import com.xnyzc.lhy.mis.entity.engine.OaRiskControlCertificate;
import com.xnyzc.lhy.mis.entity.engine.OaRiskControlRules;
import com.xnyzc.lhy.mis.entity.param.cms.engine.EngineParam;
import com.xnyzc.lhy.mis.entity.result.cms.engine.CharacteristicSnapshot;
import com.xnyzc.lhy.mis.entity.result.cms.engine.RiskEngineResult;
import com.xnyzc.lhy.mis.entity.result.cms.engine.RulesSnapshot;
import com.xnyzc.lhy.mis.mapper.dictionaries.OaSysDictMapper;
import com.xnyzc.lhy.mis.mapper.engine.OaRiskControlCertificateMapper;
import com.xnyzc.lhy.mis.mapper.engine.OaRiskControlRulesMapper;
import com.xnyzc.lhy.mis.mapper.user.OaDUserMapper;
import com.xnyzc.lhy.mis.service.engine.CmsEngineManageService;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * 风控引擎相关
 *
 * @author wangshuo
 * @date 2019-12-16 10:42
 */
@Service
public class CmsEngineManageServiceImpl implements CmsEngineManageService {

    @Autowired
    private OaSysDictMapper oaSysDictMapper;

    @Autowired
    private OaRiskControlRulesMapper oaRiskControlRulesMapper;

    @Autowired
    private OaRiskControlCertificateMapper oaRiskControlCertificateMapper;

    /**
     * 查询风控留证记录列表
     *
     * @return
     */
    @Override
    public Rv getEngineManagementList(EngineParam param) {
        if(CheckUtil.objIsEmpty(param.getLimit(),param.getPage())){
            throw PangException.create(EErrorCode.missingArg);
        }
        List<Date> timeList=param.getTimeList();
        if(CheckUtil.objIsNotEmpty(timeList)){
            if(timeList.size()==2){
                if(CheckUtil.objIsNotEmpty(timeList.get(0))){
                    param.setCreateTimeStart(new DateToStringConverter().convert(timeList.get(0)));
                }
                if(CheckUtil.objIsNotEmpty(timeList.get(1))) {
                    param.setCreateTimeEnd(new DateToStringConverter().convert(timeList.get(1)));
                }
            }else{
                throw PangException.create(EErrorCode.missingArg);
            }
        }
        List<RiskEngineResult> queryList = oaRiskControlCertificateMapper.getRiskControlList(param);
        if(!queryList.isEmpty()){
            for(RiskEngineResult query:queryList){
                query.setCreateTimeStr(new DateToStringConverter().convert(query.getCreateTime()));
            }
        }
        Integer total = oaRiskControlCertificateMapper.getRiskControlCount(param);
        Map<String, Object> map = new HashMap<>(16);
        map.put("total",total);
        map.put("queryList",queryList);
        return Rv.wrap(EErrorCode.success, map);
    }

    /**
     * 查询字典规则类型
     * @return
     */
    @Override
    public Rv getDictEngineRuleList() {
        QueryWrapper<OaSysDict> queryBusinessDict = new QueryWrapper<>();
        queryBusinessDict.eq(OaSysDict.TYPE, "engine_rule");
        List<OaSysDict> engineRuleList = oaSysDictMapper.selectList(queryBusinessDict);
        return Rv.wrap(EErrorCode.success, engineRuleList);
    }

    /**
     * 查看规则快照
     * @return
     */
    @Override
    public Rv getRulesSnapshot(Long recordId) {
        if(CheckUtil.objIsEmpty(recordId)){
            throw PangException.create(EErrorCode.missingArg);
        }
        OaRiskControlCertificate certificate=oaRiskControlCertificateMapper.selectById(recordId);
        OaRiskControlRules rules=oaRiskControlRulesMapper.selectById(certificate.getRulesId());
        RulesSnapshot snapshot=new RulesSnapshot();
        snapshot.setCharacteristicFirst(rules.getCharacteristicFirst());
        snapshot.setCharacteristicSecond(snapshot.getCharacteristicSecond());
        snapshot.setConditions(rules.getConditions());
        snapshot.setConditionsStr(ERulesConditions.find(rules.getConditions()).getDesc());
        return Rv.wrap(EErrorCode.success, snapshot);
    }

    /**
     * 查看特征快照
     * @return
     */
    @Override
    public Rv getCharacteristicSnapshot(Long recordId) {
        if(CheckUtil.objIsEmpty(recordId)){
            throw PangException.create(EErrorCode.missingArg);
        }
        OaRiskControlCertificate certificate=oaRiskControlCertificateMapper.selectById(recordId);
        BigDecimal zero=new BigDecimal(0);
        List<CharacteristicSnapshot> snapshotList=new ArrayList<>();
        if(CheckUtil.objIsNotEmpty(certificate.getPositionReport()) && certificate.getPositionReport()>0){
            CharacteristicSnapshot snapshot=new CharacteristicSnapshot();
            snapshot.setName(MessageConstant.LOCATION_REPORT);
            snapshot.setValue(certificate.getPositionReport()+MessageConstant.NUMBER);
            snapshotList.add(snapshot);
        }
        if(CheckUtil.objIsNotEmpty(certificate.getDurationTime()) && certificate.getDurationTime().compareTo(zero) == 1){
            CharacteristicSnapshot snapshot=new CharacteristicSnapshot();
            snapshot.setName(MessageConstant.ORDER_TIME);
            snapshot.setValue(certificate.getDurationTime()+MessageConstant.SECONDS);
            snapshotList.add(snapshot);
        }
        if(CheckUtil.objIsNotEmpty(certificate.getMilageDistance()) && certificate.getMilageDistance().compareTo(zero) == 1){
            CharacteristicSnapshot snapshot=new CharacteristicSnapshot();
            snapshot.setName(MessageConstant.ORDER_MILAGE);
            snapshot.setValue(certificate.getMilageDistance()+MessageConstant.METER);
            snapshotList.add(snapshot);
        }
        if(CheckUtil.objIsNotEmpty(certificate.getEstimatePrice()) && certificate.getEstimatePrice().compareTo(zero) == 1){
            CharacteristicSnapshot snapshot=new CharacteristicSnapshot();
            snapshot.setName(MessageConstant.ESTIMATE_PRICE);
            snapshot.setValue(certificate.getEstimatePrice()+MessageConstant.MONEY_NAME);
            snapshotList.add(snapshot);
        }
        if(CheckUtil.objIsNotEmpty(certificate.getTripFee()) && certificate.getTripFee().compareTo(zero) == 1){
            CharacteristicSnapshot snapshot=new CharacteristicSnapshot();
            snapshot.setName(MessageConstant.TRIP_PRICE);
            snapshot.setValue(certificate.getTripFee()+MessageConstant.MONEY_NAME);
            snapshotList.add(snapshot);
        }
        if(CheckUtil.objIsNotEmpty(certificate.getAdditionlFee()) && certificate.getAdditionlFee().compareTo(zero) == 1){
            CharacteristicSnapshot snapshot=new CharacteristicSnapshot();
            snapshot.setName(MessageConstant.ADDITION_PRICE);
            snapshot.setValue(certificate.getAdditionlFee()+MessageConstant.MONEY_NAME);
            snapshotList.add(snapshot);
        }
        return Rv.wrap(EErrorCode.success, snapshotList);
    }

    /**
     * 查询字典规则类型
     * @return
     */
    @Override
    public Rv getRiskControlNode() {
        QueryWrapper<OaSysDict> queryBusinessDict = new QueryWrapper<>();
        queryBusinessDict.eq(OaSysDict.TYPE, "risk_control_node");
        List<OaSysDict> engineRuleList = oaSysDictMapper.selectList(queryBusinessDict);
        return Rv.wrap(EErrorCode.success, engineRuleList);
    }

    /**
     * 风控规则配置列表
     * @return
     */
    @Override
    public Rv getRiskControlRulesList(Integer node) {
        if(CheckUtil.objIsEmpty(node)){
            throw PangException.create(EErrorCode.missingArg);
        }
        // 查询字典
        QueryWrapper<OaSysDict> queryBusinessDict = new QueryWrapper<>();
        queryBusinessDict.eq(OaSysDict.TYPE, "engine_rule");
        List<OaSysDict> engineRuleList = oaSysDictMapper.selectList(queryBusinessDict);
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq(OaRiskControlRules.BUSINESS_NODE,node);
        List<OaRiskControlRules> controlRulesList=oaRiskControlRulesMapper.selectList(queryWrapper);
        List<CharacteristicSnapshot> resultList=new ArrayList<>();
        if(!controlRulesList.isEmpty()){
            for(OaRiskControlRules rules:controlRulesList){
                CharacteristicSnapshot result=new CharacteristicSnapshot();
                result.setId(rules.getRulesId());
                result.setType(Integer.valueOf(rules.getRuleType()));
                result.setValue(rules.getHitCounts()+MessageConstant.NUMBER);
                for(OaSysDict dict:engineRuleList){
                    if(rules.getRuleType().equals(dict.getValue())){
                        result.setName(dict.getLabel());
                    }
                }
                resultList.add(result);
            }
        }
        return Rv.wrap(EErrorCode.success, resultList);
    }

    /**
     * 风控规则配置详情
     * @return
     */
    @Override
    public Rv getRiskControlRulesDetails(Long rulesId) {
        if(CheckUtil.objIsEmpty(rulesId)){
            throw PangException.create(EErrorCode.missingArg);
        }
        OaRiskControlRules rules=oaRiskControlRulesMapper.selectById(rulesId);
        if(CheckUtil.objIsEmpty(rules)){
            throw PangException.create(EErrorCode.unData);
        }
        RulesSnapshot snapshot=new RulesSnapshot();
        snapshot.setHitCounts(rules.getHitCounts());
        snapshot.setRulesId(rulesId);
        snapshot.setCharacteristicFirst(rules.getCharacteristicFirst());
        snapshot.setCharacteristicSecond(rules.getCharacteristicSecond());
        snapshot.setConditions(rules.getConditions());
        snapshot.setConditionsStr(ERulesConditions.find(rules.getConditions()).getDesc());
        return Rv.wrap(EErrorCode.success, snapshot);
    }

    /**
     * 风控规则配置详情
     * @return
     */
    @Override
    public Rv getUpdateRiskControlRules(RulesSnapshot param) {
        if(CheckUtil.objIsEmpty(param.getRulesId(),param.getCharacteristicFirst(),param.getHitCounts(),
                param.getCharacteristicSecond(),param.getConditions())){
            throw PangException.create(EErrorCode.missingArg);
        }
        OaRiskControlRules rules=oaRiskControlRulesMapper.selectById(param.getRulesId());
        if(CheckUtil.objIsEmpty(rules)){
            throw PangException.create(EErrorCode.unData);
        }
        rules.setConditions(param.getConditions());
        rules.setCharacteristicFirst(param.getCharacteristicFirst());
        rules.setCharacteristicSecond(param.getCharacteristicSecond());
        rules.setHitCounts(param.getHitCounts());
        rules.setUpdateTime(new Date());
        rules.setUpdateUser(TokenUtil.getTokenUserId());
        oaRiskControlRulesMapper.updateById(rules);
        return Rv.wrap(EErrorCode.success);
    }

}
